import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dartssh2/dartssh2.dart';
import '../../../common/models/server_model.dart';
import '../../../common/services/server_service.dart';
import '../../../common/utils/index.dart';

class ServerDetailController extends GetxController {
  final ServerService _serverService = Get.find<ServerService>();
  late final String serverId;
  
  Rx<ServerModel?> server = Rx<ServerModel?>(null);
  Rx<SSHClient?> sshClient = Rx<SSHClient?>(null);
  Rx<ServerStatusData?> statusData = Rx<ServerStatusData?>(null);
  
  RxBool isConnected = false.obs;
  RxBool isLoading = false.obs;
  RxString errorMessage = ''.obs;

  // 状态监听订阅
  StreamSubscription<ServerModel>? _stateSubscription;

  @override
  void onInit() {
    super.onInit();
    debugPrint('🎬 ServerDetailController: onInit');
    
    serverId = Get.parameters['id'] ?? '';
    debugPrint('   服务器ID: $serverId');
    
    if (serverId.isEmpty) {
      debugPrint('❌ ServerDetailController: 服务器 ID 为空');
      LoadingUtil.error('服务器 ID 无效');
      Get.back();
      return;
    }
    _loadServer();
    _listenToServerStateChanges();
  }

  /// 监听服务器状态变化 - 实现实时同步
  void _listenToServerStateChanges() {
    debugPrint('👂 ServerDetailController: 开始监听服务器状态变化');
    _stateSubscription = _serverService.watchServer(serverId).listen((updatedServer) {
      debugPrint('📢 ServerDetailController: 收到服务器状态更新 - ${updatedServer.name}: ${updatedServer.status.displayName}');
      
      // 更新服务器信息
      server.value = updatedServer;
      
      // 同步连接状态
      isConnected.value = _serverService.isConnected(serverId);
      sshClient.value = _serverService.getClient(serverId);
      
      debugPrint('✅ ServerDetailController: 状态已同步 - 连接状态: ${isConnected.value}');
    });
  }

  Future<void> _loadServer() async {
    debugPrint('📋 ServerDetailController: 加载服务器信息 - ID: $serverId');
    
    server.value = _serverService.getServer(serverId);
    if (server.value == null) {
      debugPrint('❌ ServerDetailController: 服务器不存在 - ID: $serverId');
      LoadingUtil.error('服务器不存在');
      Get.back();
      return;
    }
    
    debugPrint('✅ ServerDetailController: 服务器信息加载成功');
    debugPrint('   名称: ${server.value!.name}');
    debugPrint('   地址: ${server.value!.connectionString}');
    debugPrint('   状态: ${server.value!.status.displayName}');
    
    // 同步连接状态（从全局服务获取）
    isConnected.value = _serverService.isConnected(serverId);
    sshClient.value = _serverService.getClient(serverId);
    
    // 如果服务器已连接，获取状态
    if (isConnected.value) {
      debugPrint('🔗 ServerDetailController: 服务器已连接，获取监控数据');
      await fetchMonitoringData();
    }
  }

  /// 连接服务器
  Future<void> connect() async {
    debugPrint('🔌 ServerDetailController: 用户点击连接按钮');
    
    if (server.value == null) {
      debugPrint('❌ ServerDetailController: 服务器信息为空，无法连接');
      return;
    }
    
    isLoading.value = true;
    errorMessage.value = '';
    
    debugPrint('🚀 ServerDetailController: 开始连接服务器...');
    debugPrint('   服务器: ${server.value!.name}');
    debugPrint('   地址: ${server.value!.connectionString}');
    
    try {
      LoadingUtil.show('正在连接 ${server.value!.name}...');
      
      await _serverService.connectServer(serverId);
      
      // 立即同步连接状态（不等待 Stream）
      isConnected.value = _serverService.isConnected(serverId);
      sshClient.value = _serverService.getClient(serverId);
      
      debugPrint('✅ ServerDetailController: 连接成功！');
      debugPrint('   立即同步状态 - isConnected: ${isConnected.value}');
      LoadingUtil.success('连接成功！');
      
      // 自动获取监控数据
      debugPrint('📊 ServerDetailController: 自动获取监控数据...');
      await fetchMonitoringData();
    } catch (e) {
      errorMessage.value = e.toString();
      
      debugPrint('❌ ServerDetailController: 连接失败');
      debugPrint('   错误信息: $e');
      debugPrint('   错误类型: ${e.runtimeType}');
      
      LoadingUtil.error('连接失败: $e');
      
      // 状态会通过 Stream 自动同步
    } finally {
      isLoading.value = false;
      LoadingUtil.dismiss();
    }
  }

  /// 断开连接
  Future<void> disconnect() async {
    isLoading.value = true;
    
    try {
      await _serverService.disconnectServer(serverId);
      statusData.value = null;
      errorMessage.value = '';
      
      // 状态会通过 Stream 自动同步
      LoadingUtil.info('已断开连接');
    } catch (e) {
      LoadingUtil.error('断开连接失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// 获取监控数据
  Future<void> fetchMonitoringData() async {
    // 从服务直接获取连接状态（更可靠）
    final connected = _serverService.isConnected(serverId);
    
    debugPrint('📊 ServerDetailController: fetchMonitoringData');
    debugPrint('   isConnected.value: ${isConnected.value}');
    debugPrint('   _serverService.isConnected: $connected');
    
    if (!connected) {
      debugPrint('❌ ServerDetailController: 服务器未连接，无法获取监控数据');
      LoadingUtil.error('未连接到服务器');
      return;
    }
    
    isLoading.value = true;
    errorMessage.value = '';
    
    try {
      LoadingUtil.show('正在获取监控数据...');
      debugPrint('🔍 ServerDetailController: 开始执行监控脚本...');
      
      final data = await _serverService.getServerStatus(serverId);
      statusData.value = data;
      
      debugPrint('✅ ServerDetailController: 监控数据获取成功');
      debugPrint('   CPU: ${data.cpuUsage.toStringAsFixed(1)}%');
      debugPrint('   内存: ${data.memoryUsage.toStringAsFixed(1)}%');
      debugPrint('   磁盘: ${data.diskUsage.toStringAsFixed(1)}%');
      
      LoadingUtil.success('监控数据更新成功');
    } catch (e) {
      errorMessage.value = e.toString();
      debugPrint('❌ ServerDetailController: 获取监控数据失败 - $e');
      LoadingUtil.error('获取监控数据失败: $e');
      
      // 尝试使用缓存数据
      statusData.value = _serverService.getCachedStatus(serverId);
    } finally {
      isLoading.value = false;
      LoadingUtil.dismiss();
    }
  }

  /// 删除服务器
  Future<void> deleteServer() async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除服务器 "${server.value?.name ?? ''}" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        LoadingUtil.show('正在删除...');
        await _serverService.deleteServer(serverId);
        LoadingUtil.success('删除成功');
        Get.back(); // 返回到服务器列表页
      } catch (e) {
        LoadingUtil.error('删除失败: $e');
      } finally {
        LoadingUtil.dismiss();
      }
    }
  }

  @override
  void onClose() {
    debugPrint('🔚 ServerDetailController: onClose - 取消状态监听');
    _stateSubscription?.cancel();
    // 控制器关闭时不自动断开连接，保持连接状态
    super.onClose();
  }
}
